import React,{useEffect, FC} from 'react'
import { Button,Modal, Form, Input, DatePicker, Switch } from 'antd';
import { FormValues, SingleUserType } from '../data.d';
import moment from 'moment';

interface UserModelProps {
  open: boolean,
  record: SingleUserType | undefined,
  closeHandler: () => void,
  onFinish: (values: FormValues) => void,
  confirmLoading: boolean,
}

const layout = {
  labelCol: { spane: 4 },
  wrapperCol: { span: 20 },
}

const UserModal: FC<UserModelProps> = (props) => {
  const [form] = Form.useForm();
  const {open,record,closeHandler,onFinish,confirmLoading} = props

  useEffect(()=>{
    if(record === undefined){
      form.resetFields()
    } else {
      form.setFieldsValue({
        ...record,
        create_time:moment(record.create_time),
        status: record.status === 1? true : false
      });
    }
  },[ open ]);

  const onOk =()=>{
    form.submit();
  };


  const onFinishFailed = (errorInfo: any) => {
    console.log('Failed:',errorInfo);
  }

  return (
    <div>
      <Modal 
        title={record ? 'Edit ID:'+record.id : 'Add'}
        open={open} 
        onOk={onOk} 
        onCancel={closeHandler}
        confirmLoading={confirmLoading}
        forceRender
      >
        <Form 
          {...layout}
          form={form}
          name="basic"
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          initialValues={{
            status:true
          }}
        >
          <Form.Item
            label="Name"
            name="name"
            rules={[{ required: true, message: 'Please input your name!' }]}
          >
            <Input />
          </Form.Item>

          <Form.Item label="Email" name="email">
            <Input />
          </Form.Item>

          <Form.Item label="Create Time" name="create_time">
            <DatePicker showTime />
          </Form.Item>

          <Form.Item label="Status" name="status" valuePropName='checked'>
            <Switch />
          </Form.Item>

        </Form>
      </Modal>
    </div>
  )
}

export default UserModal;
